from flask import Flask, redirect, url_for, request, render_template, flash
import json, re

import _log

####################################################################################################

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def _process_num(template, keyword, param):

    nums = param.split('\n')
    count = len(nums)
    if count == 0:
        return 0, ''
    elif count == 1:
        return 1, template.replace(keyword, param)
    else:
        ret_count = count
        ret_str = ''

        try:
            begin = int(nums[0])
            end = int(nums[1])
        except:
            return 0, 'error: int(str)'

        for num in range(begin, end + 1):
            ret_str += template.replace(keyword, str(num)) + '\n'

        return ret_count, ret_str

def _process_strlist(template, keyword, param):
    strlist = param.split('\n')

    ret_count = len(strlist)
    ret_str = ''

    for str in strlist:
        ret_str += template.replace('###', str) + '\n'

    return ret_count, ret_str

# def _process_other(template, keyword, param):
    # return 0, ''

dict_type2process = {
    'num': _process_num,
    'strlist': _process_strlist,
    # 'other': _process_other,
}

@app.route('/doProcess', methods=['POST', 'GET'])
def doProcess():
    if request.method == 'POST':
        try:
            template = request.form['template']
            keyword = request.form['keyword']
            type = request.form['type']
            param = request.form['param']
        except Exception as e:
            _log.error('%s' % e)
            return 'get request.form fail!'

        ret_count = 0
        ret_str = ''

        # 数字
        if type in dict_type2process:
            ret_count, ret_str = dict_type2process[type](template, keyword, param)

        ret_json = {
            'ret_count': ret_count,
            'ret_str': ret_str
        }

        return json.dumps(ret_json)

    return 'invalid operation!'

if __name__ == '__main__':
    # 模块
    _log.init(app)

    # 网页
    app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

    app.run(
        host='127.0.0.1',
        port= 8000,
        debug=True,
        threaded=True
    )
